package pile.customer.utils;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import pile.customer.entity.SettingWechat;
import pile.customer.service.ISettingWechatService;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Log4j2
public class WxUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    // 请求token的url区分，防止覆盖正式的token
    @Value("${wxminpro.token-url}")
    public  String tokenUrl ;

    @Autowired
    private ISettingWechatService settingWechatService;


    /**
     * 接口调用凭证 access_token
     *
     * @return
     */
    public String getAccessToken(Integer channel){
        // 从缓存中获取
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String accessToken = String.valueOf(valueOperations.get("weixin:access_token:"+channel));
        if (!StringUtils.isEmpty(accessToken) && !"null".equals(accessToken)) {
            return accessToken;
        }
        //获取小程序的 appid 和secret  todo 这里需要做缓存
        SettingWechat settingWechat = settingWechatService.selectByMiniChannel(channel);

        String accessTokenUrl = tokenUrl+"?grant_type=client_credential&appid="+settingWechat.getMiniAppid()+"&secret="+settingWechat.getMiniAppsecret();
        String result = HttpClientUtil.doGet(accessTokenUrl);
        JSONObject json = JSONUtil.parseObj(result);
        String access_token = String.valueOf(json.get("access_token"));
        Long expires_in = Long.valueOf(String.valueOf(json.get("expires_in")));
        if(StringUtils.isEmpty(access_token)){
            access_token="";
        }
        // 存redis, 过期时间为7200秒-5分钟
        valueOperations.set("weixin:access_token:"+channel,access_token,expires_in-300, TimeUnit.SECONDS);
        return access_token;
    }







}